import { cacheTools, base } from 'nc-lightapp-front';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import { pageTo} from 'nc-lightapp-front';
import { getQueryCondition } from 'src/hrpub/common/utils/utils';
const { NCPopover } = base;
export default class initAction {
	constructor(comp) {
		this.comp = comp;
		if(comp.props.use){
            comp.props.use.form('psninfoheadform');
            comp.props.use.editTable('handovergrid');
			comp.props.use.cardTable('handoverdetailmygrid', 'handoverdetailgrid')
            comp.props.use.search('searchform');
        }
	}
	// 获取模板数据
	getTemplate = () => {
		const { props, action } = this.comp;
		const { createUIDom, transDimission, meta, button } = props;
		const { lang, pagecode, appcode } = transDimission;
		createUIDom({ pagecode, appcode }, (data) => {
			let handovergridDatas = data.template.handovergrid.items;
			handovergridDatas.push({
				attrcode: 'handleArea',
				itemtype: 'customer',
				hyperlinkflag: false,
				label: lang['gx6008-000046'], // 国际化 '操作'
				width: '180px',
				textAlign: 'center',
				visible: true,
				fixed: 'right',
				render: (text, record, index) => {
					return (
						<div>
							<a
								href="#"
								style={{
									color: '#0073E1',
									cursor: 'pointer',
									marginRight: '12px',
									textDecoration: 'none'
								}}
								onClick={(ev) => {
									ev.preventDefault();
									this.toCardView(record, index);
								}}
							>
								{lang['gx6008-000076'] + lang['gx6008-000123']}
							</a>
						</div>
					);
				}
			});
			handovergridDatas.forEach((item) => {
				if (item.attrcode === 'pk_bill.effectdate') {
					item.width = '130px';
				}
				if (item.attrcode === 'pk_psndoc.name') {
					item.renderStatus = 'browse';
					item.render = (value, record, index) => {
						const __text__ =
							record && record.values['pk_psndoc.name'] && record.values['pk_psndoc.name'].value
								? record.values['pk_psndoc.name'].value
								: '___';
						return (
							<a
								href="#"
								onClick={(ev) => {
									ev.preventDefault();
									this.toCardView(record, index);
								}}
							>
								{__text__}
							</a>
						);
					};
				}
			});
			// 复制一份详情页表格模板
			data.template['handoverdetailmygrid'] = deepCopy(data.template['handoverdetailgrid']);
			data.template['handoverdetailmygrid'].code = 'handoverdetailmygrid';
			data.template['handoverdetailmygrid'].name = lang['gx6008-000270'];

			const tableIdArr = [ 'handoverdetailmygrid', 'handoverdetailgrid' ];
			let detailData = [ data.template.psninfoheadform ];
			tableIdArr.forEach((val) => {
				detailData.push(data.template[val]);
				data.template.gridrelation[val] = {
					srcAreaCode: val,
					destBrowseAreaCode: null,
					destEditAreaCode: null,
					tabRelation: [ val ]
				};
			});
			tableIdArr.forEach((item) => {
				data.template[item].items.forEach((item) => {
					if (item.attrcode === 'pk_linkman.user_name') {
						item.renderStatus = 'browse';
						item.itemtype = 'customer';
						item.className = 'u-row';
						item.render = (value, record, index) => {
							const __text__ =
								record &&
								record.values['pk_linkman.user_name'] &&
								record.values['pk_linkman.user_name'].value
									? record.values['pk_linkman.user_name'].value
									: '';
							let info = [];
							if (record.values.linkmaninfo.value) {
								info = this.formatLinkmanInfoData(record.values.linkmaninfo.value);
							}

							let popoverHTML = [];
							__text__ &&
								__text__.split(',').forEach((item) => {
									let infoData = info.filter((_item_) => _item_.psnname === item) || [],
										content;
									if (!infoData.length) {
										content = (
											<div>
												<ul>
													<li>{lang['gx6008-000271'] + ':'}</li>
													<li>{lang['gx6008-000272'] + ':'}</li>
													<li>{lang['gx6008-000273'] + ':'}</li>
												</ul>
											</div>
										);
									} else {
										content = (
											<div>
												<ul>
													<li>
														{lang['gx6008-000271'] + ':'}
														{infoData.length && infoData[0].deptname}
													</li>
													<li>
														{lang['gx6008-000272'] + ':'}
														{infoData.length && infoData[0].mobile}
													</li>
													<li>
														{lang['gx6008-000273'] + ':'}
														{infoData.length && infoData[0].email}
													</li>
												</ul>
											</div>
										);
									}
									popoverHTML.push(
										<NCPopover placement="bottom" content={content} trigger="hover">
											<span className="link-main u-col-md-6">{item}</span>
										</NCPopover>
									);
								});
							return popoverHTML;
						};
					}
				});
			});
			meta.setMeta(data && data.template ? data.template : {});
			button.setButtons(data && data.button ? data.button : {});
		});
	};
	// 入离职办事项联系人信息格式化
	formatLinkmanInfoData = (data) => {
		let res = [],
			arrData = [];
		if (!data) {
			return false;
		} else {
			arrData = data.split(';');
		}
		if (arrData.length) {
			arrData.forEach((item) => {
				if (item) {
					let __arr = item.split(','),
						_data_ = {};
					__arr.forEach((_item_) => {
						let _dd = _item_.split(':');
						_data_[_dd[0]] = _dd[1];
					});
					res.push(_data_);
				}
			});
		}
		return res;
	};
	// 获取多语
	getLanguage = async () => {
		const { MultiInit, dispatch } = this.comp.props;
		return new Promise((resolve) => {
			MultiInit.getMultiLang({
				moduleId: 'gx6008',
				domainName: 'hrtrn',
				callback: (json, status, init) => {
					dispatch({
						type: 'transDimission/update',
						payload: {
							lang: json
						}
					});
					resolve();
				}
			});
		});
	};
	widget = () =>{
		const { action } = this.comp;
		action.headerAction.searchChange('widget')
	}
	// 初始化
	didMount = async () => {
		// 优先获取多语
		await this.getLanguage();
		// 其次模板
		await this.getTemplate();
		await this.getHeight();
		let type = pageTo.getUrlParam('type')
		console.log(type);
		if(type){
			setTimeout(() => {
				this.widget();
			}, 200);
		}
		// 统一订阅事件
		this.subscribe();
	};
	/* 获取当前页面可见高度 */
	getHeight = () => {
		const { transDimission } = this.comp.props;
		let wH = window.innerHeight,
			domHeight = 0,
			gap = parseInt(transDimission.pageInfo.total) === 1 ? 60 : 80;
		let hasPkOrg = JSON.stringify(transDimission.hrorgobj) === '{}' ? false : true;
		if (hasPkOrg && transDimission.hasListData) {
			domHeight += document.querySelector('.row-header') && document.querySelector('.row-header').clientHeight;
			domHeight += document.querySelector('.u-tabs') && document.querySelector('.u-tabs').clientHeight;
			domHeight += document.querySelector('.ncc-hr-pagination-wrapper')
				? document.querySelector('.ncc-hr-pagination-wrapper').clientHeight
				: 32;
		} else {
			domHeight += document.querySelector('.row-header') && document.querySelector('.row-header').clientHeight;
			domHeight += document.querySelector('.u-tabs') && document.querySelector('.u-tabs').clientHeight;
			gap = 56;
		}
		return wH - domHeight - gap;
	};
	/* tab切换 */
	tabChange = (tabIndex) => {
		const { dispatch } = this.comp.props;
		let pageInfo = {
			pageIndex: 1,
			pageSize: 10,
			total: 1,
			totalPage: 1
		};
		dispatch({
			type: 'transDimission/update',
			payload: {
				tabIndex,
				pageInfo
			}
		});
		setTimeout(() => {
			this.setTableData();
		}, 100);
	};
	/* table行双击 */
	doubleClick = (record, index) => {
		this.toCardView(record, index);
	};
	// 事件订阅部分
	subscribe = () => {
		const { comp: { action }, pubSub } = this;
		// pubSub.subscribe('getWidgetTableData', (...args) => {
		// 	action.initAction.getWidgetTableData(...args);
		// });
	};
	/*小部件表格数据展示 */
	getWidgetTableData = () =>{
		const { transDimission, dispatch, editTable } = this.comp.props;
		const { pageInfo } = transDimission;
		const { pageIndex, pageSize,totalPage,total} = pageInfo;
		let _postData_ = {
			widgetCode:"6008C090",
			pageInfo: {
				pageSize: parseInt(pageSize),
				total: parseInt(total),
				totalPage:parseInt(totalPage),
				pageIndex:  parseInt(pageIndex),
			},
			appCode:"60092070",
			pageCode:"60092070nccloud",
			areaCode:"handovergrid",
			
		};
		dispatch({
			type: 'transDimission/getWidgetTableData',
			payload: {
				postData: _postData_
			}
		}).then((res) => {
			let hasData = JSON.stringify(res.data) === '{}' ? false : true;
			if (hasData) {
				let dt = res.data.handovergrid;
				dispatch({
					type: 'transDimission/update',
					payload: {
						pageInfo: dt.pageInfo,
						hasListData: true
					}
				});
				setTimeout(() => {
					editTable.setTableData('handovergrid', dt);
					editTable.hideColByKey('handovergrid', 'handleArea')
					cacheTools.set('allpks', dt.allpks);
				}, 100);
			} else {
				editTable.setTableData('handovergrid', { rows: [] });
				cacheTools.set('allpks', []);
			}
		});
	}
	/* 设置列表页面数据 */
	setTableData = () => {
		const { transDimission, dispatch, editTable } = this.comp.props;
		const { pageInfo } = transDimission;
		const { pageIndex, pageSize } = pageInfo;
		let _ischeck_ = transDimission.tabIndex == 1 ? 'N' : 'Y';
		if (JSON.stringify(transDimission.hrorgobj) === '{}') return;
		let _postData_ = {
			type: transDimission.pagiType,
			pk_org: transDimission.hrorgobj.refpk,
			ischeck: _ischeck_,
			pageInfo: {
				pageIndex,
				pageSize
			}
		};
		dispatch({
			type: 'transDimission/getTableData',
			payload: {
				postData: Object.assign({}, _postData_, transDimission.searchData)
			}
		}).then((res) => {
			let hasData = JSON.stringify(res.data) === '{}' ? false : true;
			if (hasData) {
				let dt = res.data.handovergrid;
				dispatch({
					type: 'transDimission/update',
					payload: {
						pageInfo: dt.pageInfo,
						hasListData: true
					}
				});
				setTimeout(() => {
					editTable.setTableData('handovergrid', dt);
					cacheTools.set('allpks', dt.allpks);
					editTable.showColByKey('handovergrid', 'handleArea')
				}, 100);
			} else {
				editTable.setTableData('handovergrid', { rows: [] });
				cacheTools.set('allpks', []);
			}
		});
	};
	toSearch = () => {
		const { search, dispatch } = this.comp.props;
		let searchData = getQueryCondition(this.comp.props, 'searchform');
		dispatch({
			type: 'transDimission/update',
			payload: {
				searchData
			}
		});
		setTimeout(() => {
			this.setTableData();
		}, 100);
	};
	toCardView = (record, index) => {
		const { props, action } = this.comp;
		const { dispatch, transDimission } = props;
		dispatch({
			type: 'transDimission/update',
			payload: {
				showMode: transDimission.tabIndex === '1' ? 'card-edit' : 'card-browse'
			}
		});
		setTimeout(() => {
			action.cardAction.setDetailData(record, index);
		}, 100);
	};
}
